import React, { useEffect, useRef, useState } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  Animated,
  Keyboard,
  KeyboardEvent,
  Platform,
  TextInput,
} from "react-native";
import styles from "./index.style";
import { Ionicons } from "@expo/vector-icons";
import { ChatReply, MessageType } from "@/types/chat-message";
import { DrawerType } from "@/components/Chat/ChatDetail";
import { TextType } from "@/types/message-type";
import { FileInfo } from "@/types/file-upload";
import {useChatMessageActions, useChatMessageState} from "@/hooks/chat/chat-message";

interface QuoteButtonProps {
  /**
   * 输入框的引用，用于在引用消息时自动聚焦
   */
  textInputRef?: React.RefObject<TextInput>;

  /**
   * 设置抽屉类型的函数，用于在引用消息时设置为键盘模式
   */
  setShowDrawerType?: React.Dispatch<React.SetStateAction<DrawerType>>;
}

/**
 * 美化版本，位置调整紧贴输入框上方，可随键盘移动
 */
const QuoteButton: React.FC<QuoteButtonProps> = ({
  textInputRef,
  setShowDrawerType,
}) => {
  const { reply } = useChatMessageState()
  const { setReply } = useChatMessageActions()
  const prevReplyRef = useRef<ChatReply<TextType | FileInfo> | null>(reply);

  // 添加进入动画
  const translateY = useRef(new Animated.Value(50)).current;
  const opacity = useRef(new Animated.Value(0)).current;

  // 添加键盘位置动画
  const keyboardOffset = useRef(new Animated.Value(0)).current;
  const [keyboardHeight, setKeyboardHeight] = useState(0);

  // 监听键盘事件
  useEffect(() => {
    const keyboardWillShowListener = Keyboard.addListener(
      Platform.OS === "ios" ? "keyboardWillShow" : "keyboardDidShow",
      (e: KeyboardEvent) => {
        setKeyboardHeight(e.endCoordinates.height);
        Animated.timing(keyboardOffset, {
          toValue: e.endCoordinates.height,
          duration: Platform.OS === "ios" ? 300 : 100,
          useNativeDriver: true,
        }).start();
      }
    );

    const keyboardWillHideListener = Keyboard.addListener(
      Platform.OS === "ios" ? "keyboardWillHide" : "keyboardDidHide",
      () => {
        setKeyboardHeight(0);
        Animated.timing(keyboardOffset, {
          toValue: 0,
          duration: Platform.OS === "ios" ? 300 : 100,
          useNativeDriver: true,
        }).start();
      }
    );

    return () => {
      keyboardWillShowListener.remove();
      keyboardWillHideListener.remove();
    };
  }, []);

  // 监听reply变化，当reply出现时，显示动画并自动聚焦输入框
  useEffect(() => {
    // 当reply从无到有时，执行动画
    if (!prevReplyRef.current && reply) {
      // 执行显示动画
      Animated.parallel([
        Animated.timing(translateY, {
          toValue: 0,
          duration: 200,
          useNativeDriver: true,
        }),
        Animated.timing(opacity, {
          toValue: 1,
          duration: 200,
          useNativeDriver: true,
        }),
      ]).start();

      // 自动聚焦输入框
      if (textInputRef?.current && setShowDrawerType) {
        // 稍微延迟以确保UI更新
        setTimeout(() => {
          setShowDrawerType("keyboard");
          textInputRef.current.focus();
        }, 100);
      }
    }

    // 更新prevReplyRef
    prevReplyRef.current = reply;
  }, [reply, textInputRef, setShowDrawerType]);

  if (!reply) return null;

  // 获取消息预览文本
  const getPreviewText = () => {
    try {
      if (reply.replyMessageType === MessageType.TEXT) {
        const text =
          typeof reply.replyContent === "string"
            ? JSON.parse(reply.replyContent).text
            : reply.replyContent.text;

        // 限制长度
        return text.length > 20 ? `${text.substring(0, 20)}...` : text;
      } else if (reply.replyMessageType === MessageType.IMAGE) {
        return "[图片]";
      } else if (reply.replyMessageType === MessageType.VIDEO) {
        return "[视频]";
      } else if (reply.replyMessageType === MessageType.VOICE) {
        return "[语音]";
      }
      return "消息";
    } catch (e) {
      return "消息";
    }
  };

  // 取消引用
  const handleCancelQuote = () => {
    // 退出动画
    Animated.parallel([
      Animated.timing(translateY, {
        toValue: 50,
        duration: 150,
        useNativeDriver: true,
      }),
      Animated.timing(opacity, {
        toValue: 0,
        duration: 150,
        useNativeDriver: true,
      }),
    ]).start(() => {
      setReply(null);
    });
  };

  // 组合两个transform动画
  const combinedTranslateY = Animated.add(
    translateY,
    Animated.multiply(keyboardOffset, -1)
  );

  return (
    <Animated.View
      style={[
        styles.container,
        {
          transform: [{ translateY: combinedTranslateY }],
          opacity,
        },
      ]}
    >
      <View style={styles.quoteButton}>
        <View style={styles.quoteInfo}>
          <View style={styles.iconContainer}>
            <Ionicons name="chatbox-ellipses" size={16} color="#fff" />
          </View>
          <View style={styles.textContainer}>
            <Text style={styles.nameText}>
              引用 {reply.replyUserName} 的消息
            </Text>
            <Text style={styles.previewText} numberOfLines={1}>
              {getPreviewText()}
            </Text>
          </View>
        </View>
        <TouchableOpacity
          onPress={handleCancelQuote}
          style={styles.cancelButton}
        >
          <Ionicons name="close" size={20} color="#fff" />
        </TouchableOpacity>
      </View>
    </Animated.View>
  );
};

export default QuoteButton;
